package up7.utils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

public class PathTool {

	/**
	 * 在linux中，getName()取出来的文件名称包含路径。需要手动去掉路径部分。
	 * @param n
	 * @return
	 */
	public static String getName(String n){
		File f = new File(n);
		int pos = f.getName().lastIndexOf("\\");
		if(pos == -1) pos = f.getName().lastIndexOf("/");
		return f.getName().substring(pos+1);
	}
	
	public static String guid() {
		//简化
		return UUID.randomUUID().toString().replace("-","");
	}

	/**
	 * /a/b/c=>/a/b
	 * @param ps
	 * @return
	 */
	public static String getParent(String ps)
	{
		File f = new File(ps);
		return f.getParent();
	}

	public static String combin(String a,String b)
	{
		a = a.replace('\\', '/');
		b = b.replace('\\', '/');
		if (a.endsWith("/")) a = a.substring(0, a.length() - 1);
		if (b.startsWith("/")) b = b.substring(1);
		return a + "/" + b;
	}
	
	/**
	 * 获取父级目录名称。
	 * d:/upload/files/QQ2013.exe
	 * 返回 d:/upload/files
	 * @param p
	 * @return
	 */
	public static String getDirectoryName(String p)
	{
		File f = new File(p);
		String prt = f.getParent();
		return prt;
	}
	
	//返回值：exe
	public static String getExtention(String n)
	{
		String name = getName(n);

		int extIndex = name.lastIndexOf(".");
		//有扩展名
		if(-1 != extIndex)
		{
			String ext = name.substring(extIndex + 1);
			return ext;
		}
		return "";
	}
	
	public static Boolean exist(String v)
	{
		File f = new File(v);
		return f.exists();
	}

	public static boolean mkdir(String v){

		File fd = new File(v);
		//fix():不创建文件夹
		if(!fd.exists()) fd.mkdirs();
		return true;
	}
	
	//规范化路径，与操作系统保持一致。
	public static String canonicalPath(String v) throws IOException{
		File f = new File(v);
		return f.getCanonicalPath();
	}
	
	public static String combine(String a,String b)
	{
		boolean split = a.endsWith("\\");
		if(!split) split = a.endsWith("/");		
		//没有斜杠
		if(!split)
		{
			return a.concat("/").concat(b);
			//return ps.getCanonicalPath().replace('\\', '/');
		}//有斜框
		else{
			return a.concat(b);
			//return ps.getCanonicalPath().replace('\\', '/');
		}
	}
	/**
	 * 返回byte的数据大小对应的文本
	 * @param size
	 * @return
	 */
	public static String getDataSize(long size){
		DecimalFormat formater = new DecimalFormat("####.00");
		if(size<1024){
			return size+"bytes";
		}else if(size<1024*1024){
			float kbsize = size/1024f;  
			return formater.format(kbsize)+"KB";
		}else if(size<1024*1024*1024){
			float mbsize = size/1024f/1024f;  
			return formater.format(mbsize)+"MB";
		}else if(size<1024*1024*1024*1024){
			float gbsize = size/1024f/1024f/1024f;  
			return formater.format(gbsize)+"GB";
		}else{
			return "size: error";
		}
	}
	
	public static String url_decode(String v)
	{
		if(v== null) return "";
		if(StringUtils.isEmpty(v)) return "";
		
		v = v.replace("+","%20");
		try {
			v = URLDecoder.decode(v,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			v = "";
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//utf-8解码
		return v;
	}
	
	/**
	 * 将字符串进行urlencode编码
	 * 自动将+号替换成%20
	 * @param v
	 * @return
	 */
	public static String url_encode(String v)
	{
		if(v== null) return "";
		if(StringUtils.isEmpty(v)) return "";
		
		try {
			v = URLEncoder.encode(v,"UTF-8");
			v = v.replace("+","%20");
		} catch (UnsupportedEncodingException e) {
			v = "";
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//utf-8解码
		return v;
	}
	
	/**
	 * 将相对路径转换成绝对路径
	 * @param ps res
	 * @return /up6/imgs
	 */
	public String MapPath(String ps)
	{		
		// /up6
		String root = this.getRoot();
		
		if(StringUtils.isBlank(ps)) return root;
		
		//传值： /imgs
		if(!StringUtils.equals("/", ps.substring(0, 1))) root.contains("/");
		
		root = root.concat(ps);
		
		File f = new File(root);
		String path="";
		try {
			path = f.getCanonicalPath();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return path;
	}
	
	/**
	 * 获取项目根目录
	 * @return C:\\java\\tomcat\\7.0.47\\webapps\\up6
	 */
	public String getRoot() 
	{
		String path = this.getClass().getResource("/").getPath();
		path = path.replaceAll("//", "/");
		if(path.startsWith("/")) path = path.substring(1);
		//D:/app/tomcat/apache-tomcat-8.5.61/webapps/up6/WEB-INF/classes/
		int pos = path.indexOf("WEB-INF/classes/");
		return path.substring(0,pos);
	}
	
	public static String BytesToString(long byteCount)
	{
	    String[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
	    if (byteCount == 0)
	        return "0" + suf[0];
	    long bytes = Math.abs(byteCount);
	    int place = (new Double(Math.floor(Math.log(bytes) / Math.log(1024))).intValue());
	    double num = (double)bytes / Math.pow(1024, place);
	    num = new BigDecimal(num).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
	    return String.valueOf( (Math.signum(byteCount) * num) ) + suf[place];
	}
}
